package com.learn.io.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import jdk.nashorn.internal.runtime.DebugLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;


/**
 * @author wangxing
 * @version 2020/7/30 12:24 Administrator
 */
public class NettyClient {
    static Logger logger = LoggerFactory.getLogger(NettyClient.class);
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline channelPipeline = ch.pipeline();
                        channelPipeline.addLast("decoder",new StringDecoder());
                        channelPipeline.addLast("encode",new StringEncoder());
//                        添加客户端处理器
//                        channelPipeline.addLast(new MyNettyClientHandler());
                        channelPipeline.addLast(new CharNettyClientHandler());
                    }
                });
        System.out.println("netty client start ");
        String host = "127.0.0.1";
        Integer port = 9009;
//        启动客户端连接服务端
        ChannelFuture channelFuture =  bootstrap.connect(host,port).sync();
        Channel channel = channelFuture.channel();
        logger.info("------{}---------",channel.localAddress());
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            logger.info("send message");
            String message = scanner.nextLine();
            channel.writeAndFlush(message);
        }
//        对关闭通道进行监听
//        channelFuture.channel().closeFuture().sync();
        group.shutdownGracefully();
    }
}
